
package com.bjtg.threegoclinet;


import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.ScrollView;
import android.widget.Toast;
import android.widget.VideoView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bjfl.saleManager.util.BaiduTTSSpeakUtil;
import com.bjfl.saleManager.util.MqttUtil;
import com.bjtg.threegoclinet.base.BaseActivity;
import com.bjtg.threegoclinet.bean.ConstValue;
import com.bjtg.threegoclinet.bean.OperationBean;
import com.bjtg.threegoclinet.bean.Constants;
import com.bjtg.threegoclinet.util.JpushSharedPreferences;
import com.bjtg.threegoclinet.util.LattePreference;
import com.bjtg.threegoclinet.util.VideoUrlPath;
import com.event.MqttEvent;
import com.event.OpenDoorType;
import com.fulei.device.CSMDevice;
import com.fulei.device.EleLockDevice;
import com.fulei.device.TGGoodsDevice;
import com.log.LatteLogger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import static com.bjtg.threegoclinet.util.JpushSharedPreferences.initAppFunction;

/**
 * 程序入口
 * <p>
 * 日期:2017/04/10
 */
public class MainActivity extends BaseActivity {

    private Button openDoor, goodsOpenBtn, goodsCloseBtn, beginBtn, closeBtn, allcloseBtn,
            tempBtn, btEnv;

    private static final String TAG = "Jpush MainActivity";
    //创建货道对象
    public static TGGoodsDevice goodsDevice = new TGGoodsDevice("TGG1", "5", "9600"); //422
    //创建电磁锁对象
    public static EleLockDevice eleLockDevice = new EleLockDevice("TGEL1", "1", "9600");//232
    //压缩机对象
    public static CSMDevice csmDevice = new CSMDevice("FSK1", "6", "9600"); // 485

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 隐去标题栏（应用程序的名字）
         */
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        /**
         * 隐去状态栏部分(电池等图标和一切修饰部分)
         */
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.getWindow().getDecorView()
                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        setContentView(R.layout.activity_main);
//        moveTaskToBack(isFinishing()); //开机最小化
        EventBus.getDefault().register(this);
        LatteLogger.i("patch", "patch1");
//        intitMqtt();
        initView();
        new Thread(() -> {
            initAppFunction(MainActivity.this);
        }).start();
    }

    private void intitMqtt() {
        MqttUtil.getMqttUtilInstance().startReconnect(ConstValue.MACHINE_NO + "-Client");
    }

    private VideoView videoView;
    private Uri uri;

    public void initView() {
        videoView = (VideoView) findViewById(R.id.videoView);
        scrollView = findViewById(R.id.test_layout);

        findViewById(R.id.test_button).setOnClickListener(v -> showTestView());

        if (LattePreference.getIsFirstExecute(LattePreference.IS_FIRSTEXECUTE)) {
            showTestView();
        } else {
            showADView();
        }

    }

    private void showADView() {
        videoView.setVisibility(View.VISIBLE);
        scrollView.setVisibility(View.GONE);
        LatteLogger.d("videoPat", VideoUrlPath.VideoSavePath.toString());
        uri = Uri.parse(VideoUrlPath.VideoSavePath);
        videoView.setMediaController(new MediaController(this));
        videoView.setVideoURI(uri);
        videoView.start();
        videoView.requestFocus();
        videoView.setOnPreparedListener(mediaPlayer -> {
            mediaPlayer.setVolume(0f, 0f);
            mediaPlayer.start();
            mediaPlayer.setLooping(true);
        });
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void openDoor(MqttEvent event) {
        LatteLogger.i("mqtt", event.message.toString());
        OperationBean operationBean = JSON.parseObject(event.message.toString(),
                new TypeReference<OperationBean>() {
                });
        LatteLogger.d("mqtt", operationBean.toString());
        if (operationBean.getType().equals(OpenDoorType.BUYER.getType())) {
        } else if (operationBean.getType().equals(OpenDoorType.OPERATIONG.getType())) {
        }
    }

    private ScrollView scrollView;

    private void showTestView() {
        scrollView.setVisibility(View.VISIBLE);
        videoView.setVisibility(View.GONE);
        findViewById(R.id.adstart_button).setOnClickListener((v) -> {
            LattePreference.addIsFirstExecute(LattePreference.IS_FIRSTEXECUTE, false);
            showADView();
        });
        btEnv = findViewById(R.id.env_button);
        if (LattePreference.getIsOnline(LattePreference.IS_ONLINE)) {
            btEnv.setText("生产环境");

        } else {
            btEnv.setText("测试环境");
        }
        findViewById(R.id.env_button).setOnClickListener(v -> {
            if (LattePreference.getIsOnline(LattePreference.IS_ONLINE)) {
                btEnv.setText("测试环境");
                LattePreference.addIsOnline(LattePreference.IS_ONLINE, false);
                Toast.makeText(this, Constants.getClose(), Toast.LENGTH_LONG).show();
            } else {
                btEnv.setText("生产环境");
                LattePreference.addIsOnline(LattePreference.IS_ONLINE, true);
                Toast.makeText(this, Constants.getClose() + "---", Toast.LENGTH_LONG).show();
            }
        });
        openDoor = (Button) findViewById(R.id.openbutton);
        openDoor.setOnClickListener(v -> new Thread(() -> {
            int iret1 = eleLockDevice.CheckEleLockState();
            LatteLogger.d("test:", "<<<<<" + iret1);
            int iret2 = eleLockDevice.OpenOrCloseLeftLock(1);
            LatteLogger.d("test:", "<<<<<<" + iret2);
        }).start());

        findViewById(R.id.closebutton).setOnClickListener(v -> new Thread(() -> {
            int iret2 = eleLockDevice.OpenOrCloseLeftLock(2);

            LatteLogger.d("test:", "<<<<<<" + iret2);
        }).start());
        goodsOpenBtn = (Button) findViewById(R.id.open_button);
        goodsOpenBtn.setOnClickListener(v -> {
            LatteLogger.d("deletFile");
            new Thread(() -> {
                initAppFunction(context);
            }).start();

        });

        goodsCloseBtn = (Button) findViewById(R.id.close_button);
        goodsCloseBtn.setOnClickListener(v -> {
            try {
                //返回货道距离
                String channelListStr = "";
                for (byte j = 1; j < ConstValue.LAYERNUM; j++) {

                    if ("".equals(channelListStr)) {

                    }
                }

                LatteLogger.d("goodsTest", channelListStr);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        beginBtn = (Button) findViewById(R.id.begincsm_button);
        beginBtn.setOnClickListener(v -> openCSM());

        closeBtn = (Button) findViewById(R.id.endcsm_button);
        closeBtn.setOnClickListener(v -> closeCSM());


        allcloseBtn = (Button) findViewById(R.id.allclose_button);
        allcloseBtn.setOnClickListener(v -> {
            int iRet = csmDevice.allCloseCSM();
            if (iRet == 1) {
                Toast.makeText(context, "关闭全部设备成功:" + iRet, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "关闭全部设备失败:" + iRet, Toast.LENGTH_LONG).show();
            }

        });

        tempBtn = (Button) findViewById(R.id.tempcheck_button);
        tempBtn.setOnClickListener(v -> {

            int iRet = csmDevice.tempCheckCSM();

            BaiduTTSSpeakUtil.getInstance().speak("当前柜温:" + iRet + "℃ ");
        });
        findViewById(R.id.line_msg_button).setOnClickListener(v ->
                videoView.setOnPreparedListener(media -> media.setVolume(0.5f, 0.5f)));
    }

    private void closeCSM() {
        int iRet = csmDevice.closeCSM();
        if (iRet == 1) {
            LattePreference.addIsOpenCFM(LattePreference.IS_OPENCFM, false);
            BaiduTTSSpeakUtil.getInstance().speak("关闭压缩机成功");
        } else {
            BaiduTTSSpeakUtil.getInstance().speak("关闭压缩机失败");
        }
    }

    @Override
    protected void onDestroy() {
        JpushSharedPreferences.stopServiceMul();
        super.onDestroy();
    }

    private void openCSM() {
        int iRet = csmDevice.beginCSM();
        if (iRet == 1) {
            LattePreference.addIsOpenCFM(LattePreference.IS_OPENCFM, true);
            BaiduTTSSpeakUtil.getInstance().speak("打开压缩机成功");
        } else {
            BaiduTTSSpeakUtil.getInstance().speak("打开压缩机失败");
        }
    }

    public static boolean isNetExist;


}

